package server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Objects;

public class StaticResourceUtil {

    //获取静态资源的绝对路径
    public static String getAbsolutePath(String path){
        String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
        return absolutePath.replaceAll("\\\\","/")+path;
    }

    //读取静态资源文件输入流，通过输出流输出
    public static void outputResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        int count = 0;
        while (count==0){
            count = inputStream.available();
        }
        int resourceSize = count;
        //输出，http请求头,然后再输出内容
        outputStream.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes());

        //读取内容输出
        long written = 0;//已经读取的长度
        int bytesize = 1024;//计划缓冲的长度
        byte [] bytes = new byte[bytesize];
        while (written<resourceSize){
            if(written +bytesize>resourceSize){//说明剩余未读取长度不足一个1024长度，那就按真实长度处理
                bytesize = (int) (resourceSize-written);
                bytes = new byte[bytesize];
            }
            inputStream.read(bytes);
            outputStream.write(bytes);

            outputStream.flush();

            written+=bytesize;
        }
    }


}
